package com.example.navigation.viewModel

import android.content.Context
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.navigation.api.ResponseData
import com.example.navigation.api.navigation.NavigationApi
import com.example.navigation.api.navigation.NavigationRepository
import com.example.navigation.api.navigation.Lines
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import java.net.SocketTimeoutException
import javax.inject.Inject

/**
 * Created with IntelliJ IDEA.
 * @Author: Liao Run
 * @Date: 2024-06-10 2:02
 * @Description:
 **/
@HiltViewModel
class MapViewModel @Inject constructor(
    private val navigationRepository: NavigationRepository,
    @ApplicationContext val context: Context
) :
    ViewModel() {

    val searchRes =
        MutableStateFlow<ResponseData<Lines>>(
            ResponseData(
                0,
                "",
                null
            )
        )

    fun searchNavigationData(params: NavigationApi.SearchNavigationDataParams) {
        viewModelScope.launch {
            val responseData = try {
                navigationRepository.searchNavigationData(params)
            } catch (e: Exception) {
                if (e is SocketTimeoutException) {
                    Toast.makeText(context, "网络超时", Toast.LENGTH_SHORT).show()
                } else {
                    Toast.makeText(context, "预期之外的错误", Toast.LENGTH_SHORT).show()
                }
                Log.e(this.toString(), "searchNavigationData: $e")
                return@launch
            }
            searchRes.value = responseData
        }
    }
}